package com.upcode.weighing.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE;

public class FtpUtil {

    private static final Logger logger = LoggerFactory.getLogger(FtpUtil.class);

    private FTPClient ftpClient = null;

    /**
     * 初始化ftp服务器
     * hostname -- ftp服务器地址
     * port -- ftp服务器端口号
     * username -- ftp登录账号
     * password -- ftp登录密码
     */
    public boolean loginToFtp(String hostname,Integer port,String username,String password ) throws Exception {
        ftpClient = new FTPClient();
        ftpClient.setRemoteVerificationEnabled(false);
        ftpClient.setControlEncoding("UTF-8");

        ftpClient.connect(hostname, port); //连接ftp服务器
        ftpClient.login(username, password); //登录ftp服务器
        logger.info("connecting...ftp server  " + hostname + ":" + port);
        int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器
        if (!FTPReply.isPositiveCompletion(replyCode)) {
            logger.info("connect ftp server failed");
            return false;
        }else{
            ftpClient.enterLocalPassiveMode();
            logger.info("connect ftp server successful");
            return true;
        }
    }

    public void loginOut() throws IOException {
        if(ftpClient.isConnected()){
            ftpClient.logout();
            ftpClient.disconnect();
        }
    }

    /**
     * 上传文件
     * @param pathname ftp服务保存地址
     * @param fileName 上传到ftp的文件名
     *  @param originfilename 待上传文件的名称（绝对地址） *
     * @return
     */
    /*public boolean uploadFile( String pathname, String fileName,String originfilename){
        boolean flag = false;
        InputStream inputStream = null;
        try{
            logger.info("begin upload file "+originfilename);
            inputStream = new FileInputStream(new File(originfilename));
            ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
            createDirecroty(pathname);
            ftpClient.makeDirectory(pathname);
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.storeFile(fileName, inputStream);
            inputStream.close();
            flag = true;
            logger.info("success upload file "+originfilename);
        }catch (Exception e) {
            logger.info("failed upload file "+originfilename);
            e.printStackTrace();
        }finally{
            if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }*/
    /**
     * 上传文件
     * @param pathname ftp服务保存地址
     * @param fileName 上传到ftp的文件名
     * @param inputStream 输入文件流
     * @return
     */
    public boolean uploadFile( String pathname, String fileName,InputStream inputStream){
        boolean flag = false;
        try{
            //logger.info("begin upload file "+fileName);
            ftpClient.setFileType(BINARY_FILE_TYPE);
            createDirecroty(pathname);
            //ftpClient.makeDirectory(pathname);
            //logger.info("begin change work dir to : "+pathname);
            boolean isChangDir = ftpClient.changeWorkingDirectory(pathname);
            //logger.info("Change Work Dir = : "+isChangDir);
            /*if(!isChangDir){
                logger.info("failed change work dir to : "+pathname);
            }*/
            //logger.info("have change work dir to : "+pathname);
            ftpClient.enterLocalPassiveMode();
            //flag = ftpClient.storeFile(new String(fileName.getBytes("UTF-8"),"iso-8859-1"), inputStream);
            flag = ftpClient.storeFile(fileName, inputStream);
            inputStream.close();
            //flag = true;
            logger.info(String.format("In [%s] folder, Upload File [%S] result = [%b]",pathname,fileName,flag));
        }catch (Exception e) {
            logger.error(e.getMessage(),e);
        }finally{
            if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }




    /**
     * 创建多层目录文件，如果有ftp服务器已存在该文件，则不创建，如果无，则创建
     *
     */
    private boolean createDirecroty(String remote) throws IOException {
        boolean success = true;
        String directory = remote + "/";
        // 如果远程目录不存在，则递归创建远程服务器目录
        if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(directory)) {
            int start = 0;
            int end = 0;
            if (directory.startsWith("/")) {
                start = 1;
            } else {
                start = 0;
            }
            end = directory.indexOf("/", start);
            String path = "";
            String paths = "";
            while (true) {
                //String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
                String subDirectory = remote.substring(start, end);
                path = path + "/" + subDirectory;
                if (!existFile(path)) {
                    if (makeDirectory(subDirectory)) {
                        changeWorkingDirectory(subDirectory);
                    } else {
                        logger.info("make dir ["+subDirectory+"] failed .");
                        changeWorkingDirectory(subDirectory);
                    }
                } else {
                    changeWorkingDirectory(subDirectory);
                }

                paths = paths + "/" + subDirectory;
                start = end + 1;
                end = directory.indexOf("/", start);
                if (end <= start) {
                    break;
                }
            }
        }
        return success;
    }

    /**
     *  改变目录路径
     *
     */
    public boolean changeWorkingDirectory(String directory) {
        boolean flag = true;
        try {
            flag = ftpClient.changeWorkingDirectory(directory);
            /*if (flag) {
                logger.info("success change to direct "+directory);
            } else {
                logger.info("failed change to direct "+directory);
            }*/
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return flag;
    }

    //判断ftp服务器文件是否存在
    public boolean existFile(String path) throws IOException {
        boolean flag = false;
        FTPFile[] ftpFileArr = ftpClient.listFiles(path);
        if (ftpFileArr.length > 0) {
            flag = true;
        }
        return flag;
    }

    /**
     *
     *  创建目录
     *
     */
    public boolean makeDirectory(String dir) {
        boolean flag = true;
        try {
            flag = ftpClient.makeDirectory(dir);
            if (flag) {
                logger.info("success make direct "+dir);
            } else {
                logger.info("failed make direct "+dir);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }




    /**
     * 删除文件 *
     *
     * @param filename 要删除的文件名称 *
     * @return
     */
    /*public boolean deleteFile(String filename, String pathname) {
        ftpClient.enterLocalPassiveMode();
        boolean flag = false;
        try {
            ftpClient.changeWorkingDirectory(pathname);
            System.out.println("开始删除文件");
            flag = ftpClient.deleteFile(pathname + filename);
            ftpClient.logout();
            System.out.println("删除文件成功");
        } catch (Exception e) {
            System.out.println("删除文件失败");
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
        return true;
    }*/


    /**
     * 递归遍历出目录下面所有文件
     *
     * @param pathName 需要遍历的目录，必须以"/"开始和结束
     * @throws IOException
     */
    public void list(String pathName, List<String> arFiles) throws IOException {
        /*ftpClient.enterLocalPassiveMode();
        if (pathName.startsWith("/") && pathName.endsWith("/")) {
            String directory = pathName;
            //更换目录到当前目录
            this.ftpClient.changeWorkingDirectory(directory);
            FTPFile[] files = this.ftpClient.listFiles();
            for (FTPFile file : files) {
                if (file.isFile()) {
                    arFiles.add(directory + file.getName());
                } else if (file.isDirectory()) {
                    list(directory + file.getName() + "/", arFiles);
                }
            }
        }*/
    }

    /**
     * 递归遍历目录下面指定的文件名
     *
     * @param pathName 需要遍历的目录，必须以"/"开始和结束
     * @param ext      文件的扩展名
     * @throws IOException
     */
    public void list(String pathName, String ext, List<String> arFiles) throws IOException {
        /*ftpClient.enterLocalPassiveMode();
        if (pathName.startsWith("/") && pathName.endsWith("/")) {
            String directory = pathName;
            //更换目录到当前目录
            this.ftpClient.changeWorkingDirectory(directory);
            FTPFile[] files = this.ftpClient.listFiles();
            for (FTPFile file : files) {
                if (file.isFile()) {
                    if (file.getName().endsWith(ext)) {
                        arFiles.add(file.getName());
                    }
                } else if (file.isDirectory()) {
                    list(directory + file.getName() + "/", ext, arFiles);
                }
            }
        }*/
    }



    /*public static void main(String[] args ) throws Exception {
        FtpUtil f =  new FtpUtil();
        f.loginToFtp("124.88.100.4", 21, "ydzf", "ydzf@123");
        //ByteArrayInputStream inputStream = new ByteArrayInputStream(new FileInputStream("D:/11.png"));
        InputStream inputStream = new  FileInputStream("D:/11.png");
        boolean uplaodResult =  f.uploadFile( "/home/ydzf/testftp/aa/bb/","aaaaaaa",inputStream);
        System.out.println(uplaodResult);
    }*/

}
